package io.renren.modules.app.controller.company;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonObject;
import io.renren.common.utils.R;
import io.renren.modules.app.entity.company.CompanyEntity;
import io.renren.modules.app.entity.company.YcCompanyEntity;
import io.renren.modules.app.entity.company.YcRecordRecruitEntity;
import io.renren.modules.app.entity.index.IndexRecruitEntity;
import io.renren.modules.app.entity.index.YcRecruitEntity;
import io.renren.modules.app.service.company.CompanyUserService;
import io.renren.modules.app.utils.ALiSMSUtil;
import io.renren.utils.IpUtil;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("comuser")
public class CompanyController {

    public static Map<String,Object> phoneMap = new HashMap<>();

    private final CompanyUserService companyUserService;

    /**
     * 企业登录
     * @param map
     * @return
     */
    @PostMapping("/loginCom")
    public R loginUser(@RequestParam Map<String, Object> map){
        //调用service层登录方法，并且获取返回值
        Map<String,Object> result = companyUserService.login(map);
        return R.ok().put("result", result);
    }



    /**
     * 快捷登录
     * @param map
     * @return
     */
    @PostMapping("/loginMobile")
    public R loginMobile(@RequestParam Map<String, Object> map){
        //初始化返回值
        Map<String, Object> result = new HashMap<>();
        //获取手机号
        String mobile= map.get("mobile").toString();
        //获取验证码
        String code = map.get("code").toString();
        CompanyEntity users =  companyUserService.getOne(new QueryWrapper<CompanyEntity>().eq("mobile",map.get("mobile").toString()));
        //users不为空，即该用户已经注册过
        if(users == null){
            result.put("code",500);
            result.put("msg","该手机号未注册");
            return R.ok().put("result", result);
        }
        try{
           String concode = phoneMap.get(mobile).toString();
           if(code.equals(concode)){
               result.put("code",200);
               result.put("msg","登录成功");
               result.put("companyUser",users);
           }else{
               result.put("code",500);
               result.put("msg","手机验证码输入错误");
           }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return R.ok().put("result", result);
    }


    /**
     * 发送验证码
     * @param map
     * @return
     */
    @PostMapping("/sendCode")
    public R sendCode(@RequestParam Map<String, Object> map){
        //初始化返回值
        Map<String, Object> result = new HashMap<>();
        //获取手机号
        String mobile= map.get("mobile").toString();
        try{
            //给手机发送验证码
            String code = ALiSMSUtil.sendCode(mobile);
            //将验证码存入到map中
            phoneMap.put(mobile,code);
            result.put("msg","发送验证码成功");
            result.put("code",200);
        }catch (Exception ex){
            ex.printStackTrace();
            result.put("msg","发送验证码失败");
            result.put("code",500);
        }
        return R.ok().put("result", result);
    }


    /**
     * 公司注册
     * @param map
     * @return
     */
    @PostMapping("/registerUserCom")
    public R registerUser(@RequestParam Map<String, Object> map){
        //初始化返回值
        Map<String, Object> result = new HashMap<>();
        //根据用户名查询用户
        CompanyEntity users =  companyUserService.getOne(new QueryWrapper<CompanyEntity>().eq("account_name",map.get("accountName").toString()));
        //users不为空，即该用户已经注册过
        if(users != null){
            result.put("code",500);
            result.put("msg","该用户名已经注册过");
            return R.ok().put("result", result);
        }
        //根据手机号码查询用户
        users = companyUserService.getOne(new QueryWrapper<CompanyEntity>().eq("mobile",map.get("mobile").toString()));
        //users不为空，即该用户已经注册过
        if(users != null){
            result.put("code",500);
            result.put("msg","该手机号已经注册过");
            return R.ok().put("result", result);
        }
        //初始化用户
        CompanyEntity user = new CompanyEntity();
        //设置用户名,
        user.setAccountName (map.get("accountName").toString());
        //设置密码DigestUtils:用来给密码加密的
        user.setPassword(DigestUtils.sha256Hex(map.get("password").toString()));
        //设置手机号
        user.setMobile(map.get("mobile").toString());
        //设置注册时间  new Date()为当前时间
        user.setAddtime(new Date());
        //保存用户信息
        boolean res= companyUserService.save(user);
        if(res){
            //注册成功
            result.put("code",200);
            result.put("msg","注册成功");
        }else{
            //注册失败
            result.put("code",500);
            result.put("msg","注册失败");
        }
        return R.ok().put("result", result);
    }

    /**
     * 获取企业新增页字典数据
     */
    @RequestMapping("get/company/data")
    public @ResponseBody R getCompanyDictData () {
        R result = R.ok();
        //企业年限动态获取
        result.put("workYear", companyUserService.getWorkYearDict());
        //企业规模动态获取
        result.put("scale", companyUserService.getScaleDict());
        return result;
    }

    /**
     * 新增企业数据
     */
    @RequestMapping("save/company/data")
    public @ResponseBody YcCompanyEntity saveCompanyData (@RequestBody YcCompanyEntity company) {
        if (StringUtils.isNotEmpty(company.getCompanyName())) {
            //企业名称为空则不新增
            return companyUserService.insertYcCompanyData(company);
        }
        return null;
    }

    /**
     * 修改企业数据
     */
    @RequestMapping("update/company/data")
    public @ResponseBody boolean updateCompanyData (@RequestBody YcCompanyEntity company) {
        if (StringUtils.isNotEmpty(company.getCompanyName())) {
            //企业名称为空则不新增
            return companyUserService.updateYcCompanyData(company);
        }
        return false;
    }

    /**
     * 新增招聘人信息
     */
    @RequestMapping("save/individual/data")
    public @ResponseBody boolean saveIndividual (@RequestBody CompanyEntity company) {
        return companyUserService.insertYcCompanyUserData(company);
    }

    /**
     * 修改招聘人信息
     */
    @RequestMapping("update/individual/data")
    public @ResponseBody boolean updateIndividual (@RequestBody CompanyEntity company) {
        return companyUserService.updateYcCompanyUserData(company);
    }

    /**
     * 获取职位字典数据
     */
    @RequestMapping("get/recruit/dict")
    public @ResponseBody R getRecruitDictData () {
        R result = R.ok();
        result.put("wordYear", companyUserService.getWorkYearDict());
        result.put("edu", companyUserService.getEduBgdDict());
        result.put("positionType", companyUserService.getPositionTypeDict());
        result.put("scale", companyUserService.getRecruitSalary());
        result.put("recruitType", companyUserService.getRecruitType());
        result.put("region", companyUserService.getRegion());
        return result;
    }

    /**
     * 新增职位信息
     */
    @RequestMapping("save/recruit/data")
    public @ResponseBody boolean saveRecruitData (@RequestBody YcRecruitEntity recruitEntity) {
        System.out.println(recruitEntity);
        if (StringUtils.isNotEmpty(recruitEntity.getTitle())) {
            return companyUserService.insertYcRecruitData(recruitEntity);
        }
        return false;
    }

    /**
     * 获取职位列表数据
     */
    @RequestMapping("get/recruit")
    public @ResponseBody List<YcRecruitEntity> getRecruitList (@RequestParam("companyId") Integer companyId) {
        return companyUserService.selectRecruitList(new YcRecruitEntity().setCompanyId(companyId));
    }

    /**
     * 更新职位信息状态
     * type: 0.停用,1.启用,3.删除
     */
    @RequestMapping("update/recruit/status")
    public @ResponseBody boolean updateRecruitStatus (
            //  params: {
            //            type: '0',
            //            recruitId: item,
            //            status: 2
            //          }h和前端对应
            @RequestParam("type") String type,
            @RequestParam("recruitId") String recruitId,
            @RequestParam("status") String status) {//状态： 0.停用,1.启用,3.删除
        boolean bool = companyUserService.updateRecruitStatus(recruitId, status);//id和状态
        if (bool && ("0".equals(type) || "3".equals(type))) {//如果是0或者3，sql里字段变回1删除
            bool = companyUserService.updateRecordRecruitStatus(recruitId, true);
        }
        return bool;
    }

    /**
     * 获取职位数据
     */
    @RequestMapping("get/recruit/data")
    public @ResponseBody JSONObject getRecruitList (@RequestParam("id") String id) {
        YcRecruitEntity ycRecruitEntity = companyUserService.getRecruitData(id);
        JSONObject dataJson = new JSONObject();
        dataJson.put("recruit", ycRecruitEntity);
        return dataJson;
    }

    /**
     * 更新竞价数据
     */
    @RequestMapping("update/recruit/bid")
    public @ResponseBody boolean updateRecruitBid (
            @RequestParam("id") String id,
            @RequestParam("bid") String bid) {
        return companyUserService.updateRecruitBid(id, bid);
    }

    /**
     * 获取公司信息
     */
    @RequestMapping("get/company/detail")
    public @ResponseBody YcCompanyEntity getCompanyData (@RequestParam("id") String id) {
        return companyUserService.getCompanyData(id);
    }

    /**
     * 更新招聘职位信息
     */
    @RequestMapping("reload/recruit/date")
    public @ResponseBody boolean reloadRecruitData (@RequestParam("id") String id) {
        return companyUserService.reloadRecruitData(id);//根据id刷新职位信息
    }

    /**
     * 通过职位编号获取竞价相关数据
     */
    @RequestMapping("bid/recruit/data")
    public @ResponseBody JSONObject getBidRecruitData (
            @RequestParam("id") String id,//职位id
            @RequestParam("bidPriceRecuritId") String bidPriceRecuritId) {//竞价职位id
        return companyUserService.getBidRecruitData(id, bidPriceRecuritId);
    }

    /**
     * 通过竞价编号删除公司竞价数据
     */
    @RequestMapping("bid/delete/data")
    public @ResponseBody R getBidRecruitData (@RequestParam("companyId") Integer companyId) {
        return R.ok().put("bool", companyUserService.deleteBidRecruitData(companyId));
    }

    /**
     * 更新招聘信息
     */
    @RequestMapping("update/recruit/date")
    public @ResponseBody boolean updateRecruitData (@RequestBody YcRecruitEntity recruitEntity) {
        return companyUserService.updateRecruitData(recruitEntity);
    }

    /**
     * 更新招聘信息
     */
    @RequestMapping("update/recruit/record")
    public @ResponseBody boolean updateRecruitBidData (HttpServletRequest request,
            @RequestParam("recordId") Integer recordId,
            @RequestParam("recruitId") Integer recruitId,
            @RequestParam("userId") Integer userId) {
        String currIP = IpUtil.getIpAddr(request);
        YcRecordRecruitEntity ycRecordRecruitEntity = new YcRecordRecruitEntity();
        ycRecordRecruitEntity.setRecruitId(recruitId);
        ycRecordRecruitEntity.setAddtime(new Date());
        ycRecordRecruitEntity.setIp(currIP); // //ip地址存放到工具类里， 从request请求里解析的路径地址就ip地址
        ycRecordRecruitEntity.setUserId(userId);
        ycRecordRecruitEntity.setRecordId(recordId);
        return companyUserService.updateRecruitBidData(ycRecordRecruitEntity);
    }

    @RequestMapping("get/company/recruit/bid")
    public @ResponseBody List<IndexRecruitEntity> selectRecruitCompanyBidData () {
        return companyUserService.selectRecruitCompanyBidData();//查询全部竞价数据做排名的
    }


    /**
     * 获取招聘人信息
     */
    @RequestMapping("get/company/user/data")
    public @ResponseBody CompanyEntity getCompanyUserData (@RequestParam("id") String id) {
        if (StringUtils.isNotEmpty(id)) {
            return companyUserService.getCompanyUserData(id);
        }
        return null;
    }

    /**
     * 获取公司竞价积分
     */
    @RequestMapping("update/company/points")
    public @ResponseBody boolean updateCompanyPoints (
            @RequestParam("id") String id, @RequestParam("points") Integer points) {
        if (StringUtils.isNotEmpty(id)) {
            return companyUserService.updateCompanyPoints(id, points);
        }
        return false;
    }
}
